/**
 * <b>项目名：</b>hclv-web<br/>  
 * <b>包名：</b>com.flea.hclv.service.impl<br/>  
 * <b>文件名：</b>HHotelServiceImpl.java<br/>  
 * <b>版本信息：</b>1.0<br/>  
 * <b>日期：</b>2018年9月12日 下午3:50:38<br/>  
 * <b>COPYRIGHT 2010-2012 ALL RIGHTS RESERVED 虫子科技</b>-版权所有<br/>
 */
package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.HProductMapper;
import com.flea.hclv.model.dao.HTimeTableMapper;
import com.flea.hclv.model.dao.HVisitorOrderMapper;
import com.flea.hclv.model.entity.HProduct;
import com.flea.hclv.model.entity.HTimeTable;
import com.flea.hclv.model.entity.HVisitorOrder;
import com.flea.hclv.service.HTimeTableService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.base.util.StringUtil;
import com.flea.system.bean.FleaPage;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @description
 * @createTime 2018年9月12日 下午3:50:38
 * @modifyTime
 * @author myflea@163.com
 * @version 1.0
 */
@Service("timeTableService")
public class HTimeTableServiceImpl implements HTimeTableService {

  @Autowired
  private HTimeTableMapper timeTableMapper;
  @Autowired
  private HProductMapper hProductMapper;
  @Autowired
  private HVisitorOrderMapper hVisitorOrderMapper;

  @Override
  public List<HTimeTable> getByProductId(String productId) {
    return timeTableMapper.selectByProductId(productId);
  }

  @Override
  public boolean save(List<HTimeTable> timetables) {
    return timeTableMapper.insertList(timetables) > 0;
  }

  @Override
  public ServerResponse saveBatch(String model, HttpServletRequest request) throws Exception {
    if (StringUtil.isEmpty(model)) {
      return ServerResponse.createByErrorMessage("传入的参数为null");
    }
    JSONObject jsb = JSONObject.parseObject(model);
    if (null == jsb) {
      return ServerResponse.createByErrorMessage("参数格式化转换异常");
    }
    String productId = String.valueOf(jsb.get("productId"));
    if (StringUtil.isEmpty(productId)) {
      return ServerResponse.createByErrorMessage("产品参数为空，异常");
    }
    String timeTables = String.valueOf(jsb.get("timeTables"));
    if (StringUtil.isEmpty(timeTables)) {
      return ServerResponse.createByErrorMessage("班期参数为空，异常");
    }
    List<HTimeTable> tables = JSONObject.parseArray(timeTables, HTimeTable.class);
    if (null == tables || tables.size() == 0) {
      return ServerResponse.createByErrorMessage("班期转换结果为空，异常");
    }
    List<HTimeTable> dbTimeTables = timeTableMapper.findByProductId(productId);
    for (HTimeTable tbs: dbTimeTables
    ) {
      for (HTimeTable tb_tm: tables ) {

        if(DateUtils.isSameDay(tbs.getDate(),tb_tm.getDate())){
          return  ServerResponse.createByErrorMessage("存在同一天的产品，请检查数据，并重新尝试");
        }

      }
    }

    String orgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
    String curUser = FleaOrgUtils.getCurUserUuid(request);
    List<HTimeTable> tbs = new ArrayList<>();
    for (HTimeTable table : tables
    ) {
      table.setId(FleaStringUtils.getGenerateUUID());
      table.setCreateUser(curUser);
      table.setProductId(productId);
      tbs.add(table);
    }
    boolean result = timeTableMapper.insertList(tbs) > 0;
    if (!result) {
      throw new Exception("添加班期失败！请联系管理员");
    }
    return ServerResponse.createBySuccessMessage("班期添加成功！");
  }

  @Override
  public boolean deleteByProductIds(List<String> productIds, String userId) throws Exception {
    return timeTableMapper.deleteByProductIds(productIds) > 0;
  }

  @Override
  public ServerResponse updateTimeTable(String model, HttpServletRequest request) throws Exception {
    if (StringUtil.isEmpty(model)) {
      return ServerResponse.createByErrorMessage("传入的参数为null");
    }
    JSONObject jsb = JSONObject.parseObject(model);
    if (null == jsb) {
      return ServerResponse.createByErrorMessage("参数格式化转换异常");
    }
    String productId = String.valueOf(jsb.get("productId"));
    if (StringUtil.isEmpty(productId)) {
      return ServerResponse.createByErrorMessage("产品参数为空，异常");
    }
    HProduct p = hProductMapper.selectByPrimaryKey(productId);
    if(null==p){
      return ServerResponse.createByErrorMessage("产品为空，异常");
    }
    if(HConstant.HCLV_PRODUCT_SALE_STATUS_ONSALE.equals(p.getStatus())){
      return ServerResponse.createByErrorMessage("产品为在售状态，不可进行修改");
    }
    String timeTables = String.valueOf(jsb.get("timeTable"));
    if (StringUtil.isEmpty(timeTables)) {
      return ServerResponse.createByErrorMessage("班期参数为空，异常");
    }
    HTimeTable table = JSONObject.parseObject(timeTables, HTimeTable.class);
    if (null == table) {
      return ServerResponse.createByErrorMessage("班期转换结果为空，异常");
    }
    String timeTableId = table.getId();
    if (StringUtil.isEmpty(timeTableId)) {
      return ServerResponse.createByErrorMessage("班期ID为空，异常");
    }
    HTimeTable tableOld = timeTableMapper.selectByPrimaryKey(timeTableId);
    if(null==tableOld){
      return ServerResponse.createByErrorMessage("班期不存在，异常");
    }
    String curUser = FleaOrgUtils.getCurUserUuid(request);
    table.setModifyUser(curUser);
    boolean result = timeTableMapper.updateByPrimaryKeySelective(table)==1;
    if(!result){
      return ServerResponse.createByErrorMessage("班期更新失败");
    }
   // String orgId = FleaOrgUtils.getCurrentUserDeptUuid(request);

    return  ServerResponse.createBySuccessMessage("班期更新成功");
  }

  @Override
  public ServerResponse deleteById(String model, HttpServletRequest request) throws Exception {
    //判断该班期的产品是否在预售状态，否则不可以删除；判断此班期是否已经销售
    if (StringUtil.isEmpty(model)) {
      return ServerResponse.createByErrorMessage("传入的参数为null");
    }
    JSONObject jsb = JSONObject.parseObject(model);
    if (null == jsb) {
      return ServerResponse.createByErrorMessage("参数格式化转换异常");
    }
    String productId = String.valueOf(jsb.get("productId"));
    if (StringUtil.isEmpty(productId)) {
      return ServerResponse.createByErrorMessage("产品参数为空，异常");
    }
    String timeTableId = String.valueOf(jsb.get("timeTableId"));
    if (StringUtil.isEmpty(timeTableId)) {
      return ServerResponse.createByErrorMessage("班期参数为空，异常");
    }
    HProduct p = hProductMapper.selectByPrimaryKey(productId);
    if(null==p){
      return ServerResponse.createByErrorMessage("产品为空，异常");
    }
    if(HConstant.HCLV_PRODUCT_SALE_STATUS_ONSALE.equals(p.getStatus())){
      return ServerResponse.createByErrorMessage("产品在售状态，不可删除");
    }
    List<HVisitorOrder> visitorOrders =  hVisitorOrderMapper.selectByTimeTableId(timeTableId);
    if(null!=visitorOrders&&visitorOrders.size()>0){
      return ServerResponse.createByErrorMessage("本班期已经对外销售，不可进行删除");
    }
    boolean result = timeTableMapper.deleteByPrimaryKey(timeTableId)==1;
    if(!result){
      throw new Exception("班期删除失败");
    }
    return ServerResponse.createBySuccessMessage("班期删除成功");
  }

  @Override
  public ServerResponse<FleaPage<HTimeTable>> getByProductIdPaging(String productId, int curPage, int pageSize)
      throws Exception {
    RowBounds rowBounds = new RowBounds(curPage, pageSize);
    List<HTimeTable> list = timeTableMapper.findByProductIdPaging(rowBounds,productId);
    FleaPage<HTimeTable> pdate = new FleaPage<>(list);




//     timeTableMapper.selectByProductIdPaging(productId);
    return ServerResponse.createBySuccess(pdate);
  }

  @Override
  public ServerResponse deleteByIds(String model, HttpServletRequest request) throws Exception {
    //判断该班期的产品是否在预售状态，否则不可以删除；判断此班期是否已经销售
    if (StringUtil.isEmpty(model)) {
      return ServerResponse.createByErrorMessage("传入的参数为null");
    }
    JSONObject jsb = JSONObject.parseObject(model);
    if (null == jsb) {
      return ServerResponse.createByErrorMessage("参数格式化转换异常");
    }
    String productId = String.valueOf(jsb.get("productId"));
    if (StringUtil.isEmpty(productId)) {
      return ServerResponse.createByErrorMessage("产品参数为空，异常");
    }
    String timeTableIds = String.valueOf(jsb.get("timeTableIds"));
    if (StringUtil.isEmpty(timeTableIds)) {
      return ServerResponse.createByErrorMessage("班期参数为空，异常");
    }
    List<String> timeTableIdArrays = JSONObject.parseArray(timeTableIds,String.class);

    HProduct p = hProductMapper.selectByPrimaryKey(productId);
    if(null==p){
      return ServerResponse.createByErrorMessage("产品为空，异常");
    }
    if(HConstant.HCLV_PRODUCT_SALE_STATUS_ONSALE.equals(p.getStatus())){
      return ServerResponse.createByErrorMessage("产品在售状态，不可删除");
    }
    List<HTimeTable> timeTables = new ArrayList<>();
    for (String timeTableId:timeTableIdArrays) {
      List<HVisitorOrder> visitorOrders =  hVisitorOrderMapper.selectByTimeTableId(timeTableId);
      if(null==visitorOrders||visitorOrders.size()==0){
        boolean result = timeTableMapper.deleteByPrimaryKey(timeTableId)==1;
        if(!result){
          throw new Exception("班期删除失败");
        }
      }else{
        HTimeTable tg = new HTimeTable();
        tg.setId(timeTableId);
        timeTables.add(tg);
      }

    }
    if(timeTables.size()>0){
      return ServerResponse.createBySuccessMessage("班期删除成功,但部分班期因已经对外销售，不可进行删除");
    }
    return ServerResponse.createBySuccessMessage("班期删除成功");
  }

  @Override
  public boolean updateTimeTableRestSub(String timeTableId, int personNum,String userId) throws Exception {
  HTimeTable t =  timeTableMapper.selectByPrimaryKey(timeTableId);
  if(null==t){
    return false;
  }
  int rest = t.getRestPersonNum();
  if(rest+ personNum>=0){
    return false;
  }
  t.setModifyUser(userId);
  t.setRestPersonNum(rest+personNum);
  boolean result = timeTableMapper.updateByPrimaryKey(t)>0;
    return result;
  }

  private List<HTimeTable> codeCodeToName(List<HTimeTable> list){
    List<HTimeTable> tbs = new ArrayList<>();
    for (HTimeTable t: list) {
      t.setCreateUserName(FleaOrgUtils.getUserByUserUuid(t.getCreateUser()).getUserName());
      tbs.add(t);
    }
    return tbs;
  }



}
